package com.example.dynamicdatabase.dynamicconfig;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.example.dynamicdatabase.databasemodel.DataBaseInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Properties;

/**
 * @Description TODO
 * @Author 奶茶
 * Created by on 2018/11/26 12:15.
 */
public class CommonUtils {

    private static final Logger logger = LoggerFactory.getLogger(CommonUtils.class);

    /**
     * 动态加载数据源
     * @param dataBaseInfo
     */
    public static void dynamicSwitchDataBase(DataBaseInfo dataBaseInfo){
        Map<Object, Object> dataSourceMap = DynamicDataBaseSource.getInstance().getDataSourceMap();
        try {
            if(!dataSourceMap.containsKey(dataBaseInfo.getAppKey())){
                dataSourceMap.put(dataBaseInfo.getAppKey(),CommonUtils.createDataSource(dataBaseInfo));
                DynamicDataBaseSource.getInstance().setTargetDataSources(dataSourceMap);
            }
        } catch (Exception e) {
            logger.error("创建数据源异常：",e);
        }
        DBContextHolder.setDbType(dataBaseInfo.getAppKey());
    }

    /**
     * 创建动态数据源对象
     * @param dataBaseInfo
     * @return
     */
    private static DataSource createDataSource(DataBaseInfo dataBaseInfo) throws Exception {

        Properties properties = new Properties();

        properties.put("driverClassName", dataBaseInfo.getDriver());
        properties.put("url", dataBaseInfo.getUrl());
        properties.put("username", dataBaseInfo.getUserName());
        properties.put("password", dataBaseInfo.getPassWord());

        return DruidDataSourceFactory.createDataSource(properties);
    }

}
